package com.zhkj.shixi.tvplayer.VideoPlayer;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.SurfaceView;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.Toast;

import com.zhkj.shixi.tvplayer.Interface.PlayerInfo;
import com.zhkj.shixi.tvplayer.MyMediaPlayer;
import com.zhkj.shixi.tvplayer.PicturePlayer.CommonDialog;
import com.zhkj.shixi.tvplayer.R;
import com.zhkj.shixi.tvplayer.adapter.MyAdapter;
import com.zhkj.shixi.tvplayer.adapter.PlayList;
import com.zhkj.shixi.tvplayer.adapter.ToolListAdapter;
import com.zhkj.shixi.tvplayer.entity.ToolListEntity;

import java.io.File;
import java.io.FileFilter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class VideoPlayerActivity extends Activity implements PlayerInfo,AdapterView.OnItemClickListener {
    private static final String TAG = "VideoPlayerActivity";
    private VideoPlayerUI mVideoPlayerUI;
    private List<PlayList> mVideoList =new ArrayList<>();
    private MyMediaPlayer myMediaPlayer;
    private SurfaceView mSurfaceView;
    private File mPlayingFile;
    private BottomControlBar mPlayCtrl;
    private VideoPlayOrder mPlayOrder;
    private List<File> fileList;
    private PlayerView mPlayerView;
    private VideoFull mVideoFull;
    private ListView toolListView;
    private com.avery.subtitle.widget.SimpleSubtitleView mSubtitleView;

    private ArrayList<ToolListEntity> arrayList = new ArrayList<>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_video_player);

        mPlayCtrl = new BottomControlBar(this,this);
        myMediaPlayer = new MyMediaPlayer(VideoPlayerActivity.this);
        mPlayOrder = new VideoPlayOrder(this);
        mVideoPlayerUI = new VideoPlayerUI(this);
        mSubtitleView = findViewById(R.id.subtitle_view);
        Intent intent = getIntent();
        Toast.makeText(this,intent.getStringExtra("url"),Toast.LENGTH_SHORT).show();
        mPlayingFile = new File(intent.getStringExtra("url"));
        fileList = Arrays.asList(mPlayingFile.getParentFile().listFiles(new typeFilter()));

        initVideoList();
        MyAdapter adapter =new MyAdapter(VideoPlayerActivity.this, R.layout.item_videolist,R.id.item_videolist,mVideoList);
        mVideoPlayerUI.getListView().setAdapter(adapter);

        mVideoPlayerUI.getListView().setOnItemClickListener(this);

        mSurfaceView = findViewById(R.id.surfaceView);
        myMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                mPlayOrder.setPosition(getPlayList().indexOf(mPlayingFile));
                mPlayOrder.setOrderType(getPlayList());
                if (mPlayOrder.getType()==mPlayOrder.ORDER){
                    if (mPlayOrder.getPosition()==getPlayList().size()-1){
                        CommonDialog.Builder builder =new CommonDialog.Builder(VideoPlayerActivity.this);
                        builder.setMessage("已经是最后一个文件了");
                        builder.setTitle("提示");
                        builder.setNegativeButton("退出", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                android.os.Process.killProcess(android.os.Process.myPid());
                            }
                        });
                        builder.setPositiveButton("重新播放", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                if (mPlayOrder.getPosition() != getPlayList().size()) {
                                    mPlayingFile = getPlayList().get(mPlayOrder.getPosition());
                                    initPlayer();
                                    dialog.dismiss();

                                }

                            }
                        });
                        builder.create().show();
                    }else {
                        mPlayOrder.setPosition(mPlayOrder.getPosition()+1);
                        mPlayingFile = getPlayList().get(mPlayOrder.getPosition());
                        initPlayer();
                    }
                }else {
                    if (mPlayOrder.getPosition() != getPlayList().size()) {
                        mPlayingFile = getPlayList().get(mPlayOrder.getPosition());
                        initPlayer();
                    }
                }
            }
        });


        mPlayerView = new PlayerView(mSurfaceView,myMediaPlayer);
        setToolListView();
        mVideoFull = new VideoFull(myMediaPlayer,mPlayerView.getSurfaceView(),this);
        initPlayer();
    }



    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_DPAD_DOWN:
                //打开上下控制菜单
                if (!mVideoPlayerUI.isMenuVisiable()) {
                    mVideoPlayerUI.displayCtrlBoard();
                }
                break;
            case KeyEvent.KEYCODE_DPAD_UP:
                //打开上下控制菜单
                if (!mVideoPlayerUI.isMenuVisiable()) {
                    mVideoPlayerUI.displayCtrlBoard();
                }
                break;
            case KeyEvent.KEYCODE_MENU:
                //打开菜单面板
//                mVideoPlayerUI.changeMenuVisiblity();
                mVideoPlayerUI.slideMenuVisiblity();
                break;
            case KeyEvent.KEYCODE_DPAD_LEFT:
                mVideoPlayerUI.autoHibitCtrlBoard();
                break;
            case KeyEvent.KEYCODE_DPAD_RIGHT:
                mVideoPlayerUI.autoHibitCtrlBoard();
                break;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onBackPressed() {
        if (mVideoPlayerUI.isMenuVisiableWithoutCtrl()) {
            View setting = findViewById(R.id.setting);
            View list = findViewById(R.id.list_show);
            setting.setVisibility(View.INVISIBLE);
            list.setVisibility(View.INVISIBLE);
        } else {
            CommonDialog.Builder builder =new CommonDialog.Builder(this);
            builder.setMessage("是否退出播放");
            builder.setTitle("提醒");
            builder.setNegativeButton("退出", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    android.os.Process.killProcess(android.os.Process.myPid());
                }
            });
            builder.setPositiveButton("继续播放", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
            builder.create().show();
        }
    }

    public SurfaceView getSurfaceView() {
        return mSurfaceView;
    }

    @Override
    public File getPlayingFile() {
        return mPlayingFile;
    }

    @Override
    public void setPlayingFile(File file) {
        mPlayingFile = file;
    }

    @Override
    public List<File> getPlayList() {
        return fileList;
    }

    public MyMediaPlayer getMyMediaPlayer() {
        return myMediaPlayer;
    }

    public VideoPlayOrder getmPlayOrder() {
        return mPlayOrder;
    }

    public BottomControlBar getPlayCtrl() {
        return mPlayCtrl;
    }

    public PlayerView getPlayerView() {
        return mPlayerView;
    }



    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        setPlayingFile(fileList.get(position));
        initPlayer();
        mVideoPlayerUI.getListlayout().setVisibility(View.INVISIBLE);

    }

    public VideoFull getVideoFull() {
        return mVideoFull;
    }


    private static class typeFilter implements FileFilter
    {
        private String fileType;

        private List<String> anyType = new ArrayList<>();
        public typeFilter() {
            final List<String> videoType =  new ArrayList<>();
            videoType.add(".mp4");
            videoType.add(".3gp");
            videoType.add(".wmv");
            videoType.add(".ts");
            videoType.add(".rmvb");
            videoType.add(".mov");
            videoType.add(".m4v");
            videoType.add(".avi");
            videoType.add(".m3u8");
            videoType.add(".3gpp");
            videoType.add(".3gpp2");
            videoType.add(".mkv");
            videoType.add(".flv");
            videoType.add(".divx");
            videoType.add(".f4v");
            videoType.add(".rm");
            videoType.add(".asf");
            videoType.add(".ram");
            videoType.add(".mpg");
            videoType.add(".v8");;
            videoType.add(".swf");
            videoType.add(".m2v");
            videoType.add(".asx");
            videoType.add(".ra");
            videoType.add(".ndivx");
            videoType.add(".xvid");
            anyType = videoType;
        }
        public boolean accept(File file) {
            for(int i = 0;i < anyType.size();i++) {
                if(file.getName().toLowerCase().endsWith(anyType.get(i))){
                    return true;
                }
                else if(file.isDirectory()){
                    return false;
                }
            }
            return false;
        }
    }

    @Override
    protected void onDestroy() {
        myMediaPlayer.getmSubtitleView().destroy(); // 记得销毁
        super.onDestroy();
    }

    public void initPlayer() {
        myMediaPlayer.setmSubtitleView(mSubtitleView);
        mPlayerView.surfaceCreated(mPlayerView.getHolder());
        myMediaPlayer.init(mPlayingFile.getAbsolutePath(),mPlayerView.getHolder());
        myMediaPlayer.play();
        mVideoPlayerUI.upgradeUI();
        mVideoFull.setFull();
    }
    private void initVideoList(){
        for (File file:fileList){
            PlayList f =new PlayList(file.getName());
            mVideoList.add(f);
        }
        Log.i(TAG, "initVideoList: "+mVideoList.size());
    }

    public void setToolListView(){
        toolListView =(ListView)findViewById(R.id.setting_list_view);
        Log.d(TAG, "setToolListView");
        ToolListEntity subtitleEntity = new ToolListEntity(R.drawable.player_video_list_icn_subtitle_normal_selector,"字幕");
        arrayList.add(subtitleEntity);
        ToolListEntity orderEntity = new ToolListEntity(R.drawable.player_video_list_icn_order_normal_selector,"顺序");
        arrayList.add(orderEntity);
        Log.i(TAG, "setToolListView: "+arrayList);
        ToolListAdapter adapter = new ToolListAdapter(VideoPlayerActivity.this,R.layout.tool_setting_item,arrayList);
        toolListView.setAdapter(adapter);

//          测试
//        String[] strs = {"基神","B神","翔神","曹神","J神"};
//        ArrayAdapter<String> adapter = new ArrayAdapter<String>
//                (this,android.R.layout.simple_expandable_list_item_1,strs);
//        //获取ListView对象，通过调用setAdapter方法为ListView设置Adapter设置适配器
//        toolListView.setAdapter(adapter);

        toolListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (position == 0){
                    initSubtitlePop(view);
                }else{
                    initOrderPop(view);
                }
            }
        });
    }

    private void initSubtitlePop(View v) {
        View view = LayoutInflater.from(this).inflate(R.layout.subtitle_popupwindow, null, false);
        Button btnShowSubtitle = (Button) view.findViewById(R.id.subtitle_show);
        Button btnCloseSubtitle= (Button) view.findViewById(R.id.subtitle_close);
        //1.构造一个PopupWindow，参数依次是加载的View，宽高
        final PopupWindow popWindow = new PopupWindow(view, 180, 180, true);
        //这些为了点击非PopupWindow区域，PopupWindow会消失的，如果没有下面的
        //代码的话，你会发现，当你把PopupWindow显示出来了，无论你按多少次后退键
        //PopupWindow并不会关闭，而且退不出程序，加上下述代码可以解决这个问题
        popWindow.setTouchable(true);
        popWindow.setTouchInterceptor(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return false;
                // 这里如果返回true的话，touch事件将被拦截
                // 拦截后 PopupWindow的onTouchEvent不被调用，这样点击外部区域无法dismiss
            }
        });
        popWindow.setBackgroundDrawable(new ColorDrawable(0x00000000)); //要为popWindow设置一个背景才有效
        //设置popupWindow显示的位置，参数依次是参照View，x轴的偏移量，y轴的偏移量
        popWindow.showAsDropDown(v, -180, -110);
        //设置popupWindow里的按钮的事件
        btnShowSubtitle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                findViewById(R.id.subtitle_view).setVisibility(View.VISIBLE);
            }
        });
        btnCloseSubtitle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

//                Toast.makeText(VideoPlayerActivity.this, "关闭字幕", Toast.LENGTH_SHORT).show();
//                popWindow.dismiss();

                findViewById(R.id.subtitle_view).setVisibility(View.INVISIBLE);
            }
        });
    }

    private void initOrderPop(View v) {
        View view = LayoutInflater.from(this).inflate(R.layout.order_popupwindow, null, false);
        Button btnSinglePlay = (Button) view.findViewById(R.id.order_single);
        Button btnOrderedPlay= (Button) view.findViewById(R.id.order_ordered);
        Button btnCyclePlay= (Button) view.findViewById(R.id.order_cycle);
        Button btnRandomPlay= (Button) view.findViewById(R.id.order_random);
        //构造一个PopupWindow，参数依次是加载的View，宽高
        final PopupWindow popWindow = new PopupWindow(view, 180, 260, true);
        popWindow.setTouchable(true);
        popWindow.setTouchInterceptor(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return false;
                // 这里如果返回true的话，touch事件将被拦截
                // 拦截后 PopupWindow的onTouchEvent不被调用，这样点击外部区域无法dismiss
            }
        });
        popWindow.setBackgroundDrawable(new ColorDrawable(0x00000000));    //要为popWindow设置一个背景才有效

        //设置popupWindow显示的位置，参数依次是参照View，x轴的偏移量，y轴的偏移量
        popWindow.showAsDropDown(v, -180, -110);

        //设置popupWindow里的按钮的事件
        btnSinglePlay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPlayOrder.setType(VideoPlayOrder.SINGLE);
                Toast.makeText(VideoPlayerActivity.this, "单集播放", Toast.LENGTH_SHORT).show();
                popWindow.dismiss();

            }
        });
        btnOrderedPlay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPlayOrder.setType(VideoPlayOrder.ORDER);
                Toast.makeText(VideoPlayerActivity.this, "顺序播放", Toast.LENGTH_SHORT).show();
                popWindow.dismiss();
            }
        });
        btnCyclePlay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPlayOrder.setType(VideoPlayOrder.CYCLE);
                Toast.makeText(VideoPlayerActivity.this, "循环播放", Toast.LENGTH_SHORT).show();
                popWindow.dismiss();
            }
        });
        btnRandomPlay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPlayOrder.setType(VideoPlayOrder.RAND);
                Toast.makeText(VideoPlayerActivity.this, "随机播放", Toast.LENGTH_SHORT).show();
                popWindow.dismiss();
            }
        });
    }
}
